const mysql = require('../mysql/index')
const fs = require('fs')
const path = require('path')

var fn_index = async (ctx, next) => {
  var data = fs.readFileSync(path.resolve(__dirname + '../../dist/index.html'));
  ctx.response.body = data.toString('utf-8');
};

var fn_signin = async (ctx, next) => {
  var name = ctx.request.body.name || '', password = ctx.request.body.password || '';
  console.log(`signin with name: ${name}, password: ${password}`);
  if (name === 'koa' && password === '12345') {
    ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
  } else {
    ctx.response.body = `<h1>Login failed!</h1>
      <p><a href="/">Try again</a></p>`;
  }
};

var test_sql_all = async (ctx, next) => {
  let data = await mysql.queryAll(ctx.request.body.sqlName);
  ctx.response.body = {
    code: '00',
    data: data,
    message: 'success'
  }
}
var testWhere = async (ctx, next) => {
  let req = ctx.request.body;
  let data = await mysql.queryWhere(req.sqlName, req.condition);
  ctx.response.body = {
    code: '00',
    data: data,
    message: 'success'
  }
}

var testUpdate = async (ctx, next) => {
  let req = ctx.request.body;
  let change = await mysql.update(req.sqlName, req.condition, req.newValue);
  ctx.response.body = {
    code: '00',
    message: 'success'
  }
}

var testDelete = async (ctx, next) => {
  let req = ctx.request.body;
  let data = await mysql.delete(req.sqlName, req.condition)
  ctx.response.body = {
    code: '00',
    message: 'success',
    data: data
  }
}

var testInsert = async (ctx, next) => {
  let req = ctx.request.body;
  let data = await mysql.insert(req.sqlName, req.keys, req.values);
  ctx.response.body = {
    code: '00',
    message: 'success',
    data: data
  }
}
module.exports = {
  'GET /': fn_index,
  'POST /signin': fn_signin,
  'POST /testSql': test_sql_all,
  'POST /testWhere': testWhere,
  'POST /testUpdate': testUpdate,
  'POST /testDelete': testDelete,
  'POST /testInsert': testInsert
};